<template>
    <div class="carGate">


        <div class="searchPart">
            <SectionTitle text="车辆备案查询"></SectionTitle>
            <div class="search">
                <van-search v-model="key" show-action placeholder="车牌号 " @search="onSearch">
                    <template #action>
                        <div class="carSearchBtns">
                            <van-button @click="onSearch"   type="primary">搜索</van-button>

                            <van-button id="openCamera2" type="primary"   :icon="iconPhoto"
                                class="takePhoto">拍车牌</van-button>
                        </div>
                    </template>
                </van-search>
            </div>

            <van-dropdown-menu auto-locate>
                <van-dropdown-item v-model="value2" :options="option2" teleport="body" @change="handleSelectChange" @click="handleSelectChange" />
                <van-dropdown-item v-model="value1" :options="option1" teleport="body" @change="handleSelectChange" />                
                <van-dropdown-item v-model="value3" :options="option3" teleport="body" @change="handleSelectChange" />
            </van-dropdown-menu>

            <input type="file" accept="image/*" id="cameraInput2" style="display:none;" capture="environment">

            <div class="previewWrapperClass" style="display:none;" id="previewWrapper2">
                <img id="preview2" class="previewImg" />

                <div style="    text-align: center;
                        margin-top: 10px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        ">正在上传，请稍后
                    <van-loading />
                </div>
            </div>

        </div>

        <div class="searchResult">
            <van-empty description="未查询到车辆备案信息" v-if="nodata" />

            <van-pull-refresh v-model="refreshing" @refresh="onRefresh" v-if="!nodata">

                <div class="asynDate" v-if="asynDate" style="margin-bottom: 0;margin-top: 12px;">
                    数据更新日期：{{ asynDate }}<br/>
                    <span class="asynDateDesc">按车辆备案时间排序</span>
                </div>

                <van-list class="carInfoList" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
                    @load="onLoad">
                    <ColorItem color="#FFA000" class="searchItem" :colorBorder="false" v-for="cardInfo in carInfoList">
                        <CarInfoItem :value="cardInfo" show-btns />
                    </ColorItem>
                </van-list>
            </van-pull-refresh>
        </div>
    </div>

    <van-calendar v-model:show="showCalendar" type="range" @confirm="onConfirmCalendar" teleport="body" :min-date="minDate" :max-date="maxDate"/>

</template>
<script lang="ts" setup>

import CarInfoItem from '@/components/carInfo.vue';
import ColorItem from '@/components/ColorItem.vue';
import iconPhoto from '@/assets/icons/icon_photo.png'
import http from '@/api/request'
import SectionTitle from '@/components/SectionTitle.vue';
import { onMounted, ref } from 'vue';
import { type CarQueryResult, type CarInfo } from '@/types/common';
import { saveLog } from '@/api/queryLog';
import axios from 'axios';
import DialogTool from '@/util/DialogTool';
import { formateDateYMD } from '@/util/dateTool';

const nodata = ref(false);
const key = ref('')

const carInfoList = ref<CarInfo[]>([]);
const asynDate = ref('')
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false);
const value1 = ref(0);
const value2 = ref(0);
const value3 = ref(0)
const showCalendar = ref(false)
const beginDate = ref('')
const endDate = ref('')

const minDate= new Date(2010, 0, 1);
const maxDate= new Date(2050, 0, 31);

var pageNo = 1;



const option1 = [
    { text: '所有车辆', value: 0 },
    { text: '教职工车辆', value: 4 },
    { text: '学生车辆', value: 3 },
    { text: '学校公车', value: 2 },
    { text: '大客车', value: 1 },
];
const option2 = ref([
    { text: '入校日期', value: 0 },
    { text: '今天', value: 1 },
    { text: '未来三天', value: 2 },
    { text: '未来一个月', value: 3 },
    { text: '其他日期', value: -1 },
]);

const option3 = [
    { text: '乘客数量', value: 0 },
    { text: '1人-10人', value: 1 },
    { text: '10人-20人', value: 2 },
    { text: '20人-30人', value: 3 },
    { text: '30人-40人', value: 4 },
    { text: '40人以上', value: 5 },
];

const onSearch = () => {

    pageNo = 1;
    saveLog("查询车辆备案", "tab_car", key.value)

    getList();
}

onMounted(() => {
    pageNo = 1;
    getList();

    initTakePhoto();

})

const handleSelectChange = () => {

    if(value2.value == -1){ //选择其他日期
        showCalendar.value = true;        
    }else{
        beginDate.value = ''
        endDate.value= ''
        pageNo = 1;
        getList();
    }

    
}

const onConfirmCalendar =  (values:Date[]) => {
      const [start, end] = values;
      showCalendar.value = false;
      beginDate.value = formateDateYMD(start);
      endDate.value = formateDateYMD(end);     

      var opt = option2.value;
      opt[4].text = beginDate.value+"至"+endDate.value;
      option2.value = opt;

      pageNo = 1;
      getList();
};


const getList = () => {
    http.get<CarQueryResult>('/query/queryCar/', {
        key: key.value, pageNo,
        query1: value1.value,
        query2: value2.value,
        query3: value3.value,
        beginDate:beginDate.value,
        endDate:endDate.value
    }).then((resp) => {
        loading.value = false;
        refreshing.value = false;
        nodata.value = false;

        if (pageNo == 1) carInfoList.value = [];

        var result = resp.data?.carInfoList;
        if (result && result.length > 0) {
            nodata.value = false;
            carInfoList.value = carInfoList.value.concat(result);
        } else {
            if (pageNo == 1) nodata.value = true;
            finished.value = true;
        }

        if (resp.data?.asynDate) asynDate.value = resp.data?.asynDate
    })
}

const onLoad = () => {
    if (pageNo == 1 && carInfoList.value.length == 0) { //初始化，不加载
        loading.value = false;
        return;
    }

    pageNo++;
    getList();
}

const onRefresh = () => {
    pageNo = 1;
    finished.value = false;
    getList();
}


const initTakePhoto = () => {

    document.getElementById('openCamera2')?.addEventListener('click', function () {
        document.getElementById('cameraInput2')?.click();
    });

    document.getElementById('cameraInput2')?.addEventListener('change', function (event) {
        //@ts-ignore
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const preview = document.getElementById('preview2');
                if (preview) {
                    //@ts-ignore
                    preview.src = e.target.result;
                    preview.style.display = 'block';

                    const previeWrapper = document.getElementById('previewWrapper2');
                    if (previeWrapper) {
                        previeWrapper.style.display = 'block';
                    }

                }

            }
            reader.readAsDataURL(file);

            //开始上传
            const formData = new FormData();
            formData.append('file', file);

            // 定义用户名和密码
            const username = 'carocr';
            const password = 'Tju@1885';

            // 创建认证的基本信息
            const basicAuth = 'Basic ' + btoa(`${username}:${password}`);


            axios.post('/api/v1/ocr', formData, {
                headers: {
                    'Authorization': basicAuth
                }
            })
                .then((resp) => {
                    const result = resp.data.result.plate_list;

                    const previeWrapper = document.getElementById('previewWrapper2');
                    if (previeWrapper) {
                        previeWrapper.style.display = 'none';
                    }

                    if (result.length > 0) {
                        var code = result[0].code;
                        key.value = code;
                        onSearch();


                    } else {

                        DialogTool.showAlert("未识别出车牌号，请重新拍照！")

                    }
                });

        }
    });
}

</script>

<style lang="less" scoped>
.carGate {

    min-height: 100vh;



    .searchPart {
        margin-top: 60px;
        background-color: #fff;

        padding: 10px;
        padding-bottom: 0;

        .search {
            margin-top: 10px;
        }
    }

    .searchResult {


        .sectionTitleWrapper {
            margin-top: 2px;
            background-color: #fff;
            padding: 10px;
        }

        .subSection {
            line-height: 30px;
        }

        .carInfoList {
            padding: 10px;

            .searchItem {
                margin-bottom: 10px;
                background-color: #fff;
            }
        }
    }


    .searchSummary {
        font-size: 14px;
        padding: 10px;
        padding-bottom: 0;
        text-align: center;
    }
}

.carInLog {
    background-color: #f2f2f2;
    min-height: 100vh;

    .detailTitleCarLOg {
        text-align: center;
        line-height: 40px;
        font-size: 18px;
        margin-top: 10px;
    }
}

.carSearchBtns {
    display: flex;
    align-items: center;
}


.previewImg {
    width: 100%;
    border-radius: 10px;
}

.previewWrapperClass {
    padding: 40px;
    background-color: #fff;
}
</style>

<style>
.carGate .van-search__content {
    border-radius: 0;
    border: 1px solid #004e9b;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    border-right: none;
}

.carGate .van-search__field {
    height: 42px;
}

.carGate .van-search__action {
    padding-left: 0;
}

.carGate .van-search__action .van-button {
    border-radius: 0;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
</style>